package gim_broker

import (
	"net"
	"time"
)

var (
	removeClient chan *net.TCPConn
)

type heartBeatInfo struct {
	conn        net.Conn    // 客户端连接
	lastMessage time.Time   // 上次收到心跳的时间
	heartbeat   chan []byte // 心跳消息通道
}

func NewHeartBeatInfo(conn net.Conn) *heartBeatInfo {
	h := &heartBeatInfo{
		conn:        conn,
		lastMessage: time.Now(),
		heartbeat:   make(chan []byte),
	}
	return h
}

// 心跳检测
func heartBeatDetection(conn *net.TCPConn, c *heartBeatInfo) {

	//c := NewHeartBeatInfo(conn)
	go func() {
		for {
			select {
			case <-c.heartbeat:
				c.lastMessage = time.Now()
			}
		}
	}()
	for {
		if time.Since(c.lastMessage) > (3 * 15 * time.Second) {
			// 客户端超时未发送心跳消息，移除客户端
			removeClient <- conn
			return
		}
		time.Sleep(1 * time.Second)
	}
}

// 移除丢失心跳的客户端
func removeInvalidClient() {
	for {
		select {
		case conn := <-removeClient:
			// 移除客户端连接 以及相关资源
			releaseByConn(conn)
		}
	}
}

func InitHeartBeat() {

	removeClient = make(chan *net.TCPConn)
}
